package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.controller.vo.ShowInfoVo;
import com.hunttown.mes.manage.service.MesEquipmentExamineManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.MesEquipmentExamineProjectManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.MesEquipmentExamineDTO;
import com.hunttown.mes.rpc.domain.MesEquipmentExamineProjectDTO;
import com.hunttown.mes.rpc.domain.enums.mes.examine.ExamineFrequencyEnum;
import com.hunttown.mes.rpc.domain.enums.mes.examine.ExamineStatusEnum;
import com.hunttown.mes.rpc.domain.query.MesEquipmentExamineDTOQuery;
import com.hunttown.mes.rpc.domain.query.MesEquipmentExamineProjectDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-03-30 15:25:22
 */
@Controller
@RequestMapping(value = "/mes/equipment-examine")
public class MesEquipmentExamineController {

    private final static Logger logger = LoggerFactory.getLogger(MesEquipmentExamineController.class);

    private final MesEquipmentExamineManageService mesEquipmentExamineService;
    private final MesEquipmentExamineProjectManageService examineProjectService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;

    @Autowired
    public MesEquipmentExamineController(MesEquipmentExamineManageService mesEquipmentExamineService, MesEquipmentExamineProjectManageService examineProjectService, AnalysisManageManageService manageService, ModelService modelService) {
        this.mesEquipmentExamineService = mesEquipmentExamineService;
        this.examineProjectService = examineProjectService;
        this.manageService = manageService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, MesEquipmentExamineDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by id desc");
        Page<MesEquipmentExamineDTO> dataPage = mesEquipmentExamineService.getForPage(dtoQuery);

        MesEquipmentExamineProjectDTOQuery projectQuery;

        for (MesEquipmentExamineDTO item : dataPage.getItems()) {
            item.setEquipName(modelService.getMesEquipName(item.getEquipId()));
            item.setExaminePeopleCn(modelService.getManageName(item.getExaminePeople()));
            item.setStatusName(ExamineStatusEnum.getEnumByKey(item.getStatus()));

            //获取维护项目
            projectQuery = new MesEquipmentExamineProjectDTOQuery();
            projectQuery.setTableId(185);
            projectQuery.setRecordId(item.getId());
            Page<MesEquipmentExamineProjectDTO> projectPage = examineProjectService.getForPage(projectQuery);
            item.setProjectList(projectPage.getItems());
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        //设备列表
        modelService.getMesEquipmentPage(model);

        //region 页面按钮权限
        String pin = AdminBaseClass.getPin(request);
        String[] menus = {"J-W-JXJL-BJ", "J-W-JXJL-SC", "J-W-JXJL-QTY"};
        model.addAttribute("Permission", manageService.GetBtnPermission(menus, pin));
        //endregion

        return "mes/equipment-examine/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id) {
        id = (id == null ? 0 : id);

        MesEquipmentExamineDTO obj;

        if (id > 0) {
            obj = mesEquipmentExamineService.getById(id);

            //region 获取已保存的维护项目
            MesEquipmentExamineProjectDTOQuery projectQuery = new MesEquipmentExamineProjectDTOQuery();
            projectQuery.setTableId(185);
            projectQuery.setRecordId(id);
            Page<MesEquipmentExamineProjectDTO> projectPage = examineProjectService.getForPage(projectQuery);
            model.addAttribute("projectList", projectPage.getItems());
            //endregion

        } else {
            obj = new MesEquipmentExamineDTO();
            obj.setId(0);
            obj.setExamineTime(new Date());
            obj.setStatus(1);

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            obj.setExaminePeople(curr_obj.getId());
        }
        model.addAttribute("Obj", obj);

        //设备列表
        modelService.getMesEquipmentPage(model);

        //检修人
        modelService.getManagerPage(model);

        model.addAttribute("examineStatusList", ExamineStatusEnum.getEnumList());
        model.addAttribute("examineFrequencyList", ExamineFrequencyEnum.getEnumList());

        return "mes/equipment-examine/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, MesEquipmentExamineDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //日期
            objDTO.setExamineTime(DateConvertUtils.strToDate(objDTO.getExamineTimeSr()));

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);

                objDTO = mesEquipmentExamineService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = mesEquipmentExamineService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }


            //region [01].维护项目表.保存成功后更新
            String[] f_id = request.getParameterValues("f_id");
            String[] f_projectid = request.getParameterValues("f_projectid"); //cate_id
            String[] f_projectname = request.getParameterValues("f_projectname");

            //1.获取已保存的维护项目
            MesEquipmentExamineProjectDTOQuery historyQuery = new MesEquipmentExamineProjectDTOQuery();
            historyQuery.setTableId(185);
            historyQuery.setRecordId(objDTO.getId());
            historyQuery.setPageSize(100);
            Page<MesEquipmentExamineProjectDTO> historyPage = examineProjectService.getForPage(historyQuery);

            //2. 保存到数据库
            if (f_id != null && f_id.length > 0) {

                List<Integer> newProjectIds = new ArrayList<>(); //提交上来的，已保存过的ID
                MesEquipmentExamineProjectDTO insert;

                for (int i = 0; i < f_id.length; i++) {
                    insert = new MesEquipmentExamineProjectDTO();
                    insert.setTableId(185);
                    insert.setRecordId(objDTO.getId());
                    insert.setCateId(Integer.parseInt(f_projectid[i]));
                    insert.setProjectName(f_projectname[i]);
                    insert.setDeleteFlag(0);

                    //更新或插入
                    int id = Integer.parseInt(f_id[i]);
                    if (id > 0) {
                        //更新
                        newProjectIds.add(id);
                        insert.setId(id);
                        examineProjectService.updateInfoById(insert);
                    } else {
                        //插入
                        examineProjectService.insert(insert);
                    }
                }

                //3.不存在新列表中的则表示已经删除了
                for (MesEquipmentExamineProjectDTO item : historyPage.getItems()) {
                    if (!newProjectIds.contains(item.getId())) {
                        examineProjectService.delete(item.getId());
                    }
                }
            }
            //endregion


            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = mesEquipmentExamineService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = mesEquipmentExamineService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        MesEquipmentExamineDTO obj = new MesEquipmentExamineDTO();
        obj.setId(id);

        if (id > 0) {
            obj = mesEquipmentExamineService.getById(id);
        }
        model = mesEquipmentExamineService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //详情
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public String getInfo(Model model, Integer id) {

        //显示标题
        String showTitle = "未知";

        //数据
        ShowInfoVo vo;
        List<ShowInfoVo> dataList = new ArrayList<>();

        if (id != null && id > 0) {
            MesEquipmentExamineDTO obj = mesEquipmentExamineService.getById(id);

            if (obj != null) {
                showTitle = modelService.getMesEquipName(obj.getEquipId()) + "检修";

                vo = new ShowInfoVo();
                vo.setKey("编号ID");
                vo.setValue(obj.getId());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("设备名称");
                vo.setValue(modelService.getMesEquipName(obj.getEquipId()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("检修频率");
                vo.setValue(ExamineFrequencyEnum.getEnumByKey(obj.getExamineFrequency()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("检修内容");

                MesEquipmentExamineProjectDTOQuery projectQuery = new MesEquipmentExamineProjectDTOQuery();
                projectQuery.setTableId(185);
                projectQuery.setRecordId(obj.getId());
                Page<MesEquipmentExamineProjectDTO> projectPage = examineProjectService.getForPage(projectQuery);

                List<String> ExamineNameList = new ArrayList<>();
                for (MesEquipmentExamineProjectDTO item : projectPage.getItems()) {
                    ExamineNameList.add(item.getProjectName());
                }

                vo.setValue(String.join("</br>", ExamineNameList));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("检&ensp;修&ensp;人");
                vo.setValue(modelService.getCatalogName(obj.getExaminePeople()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("检修时间");
                vo.setValue(obj.getExamineTimeSr());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("检修结果");
                vo.setValue(obj.getExamineResult());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("发现问题");
                vo.setValue(obj.getDiscoverProblem());
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("检修状态");
                vo.setValue(ExamineStatusEnum.getEnumByKey(obj.getStatus()));
                dataList.add(vo);

                vo = new ShowInfoVo();
                vo.setKey("备注说明");
                vo.setValue(obj.getRemark());
                dataList.add(vo);
            }

            model.addAttribute("showTitle", showTitle);
            model.addAttribute("dataList", dataList);
        }

        return "show/getinfo-template";
    }

    //endregion

}